package com.lagou.handler;

import com.lagou.rpc.RpcRequest;
import com.lagou.rpc.RpcResponse;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;

import java.lang.reflect.Method;

public class UserServerHandler extends ChannelInboundHandlerAdapter {
    Logger logger = LoggerFactory.getLogger(UserServerHandler.class);

    private ApplicationContext applicationContext;

    public UserServerHandler(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        Exception exception = null;
        RpcRequest rpcRequest = (RpcRequest) msg;
        Object result = null;
        try {
            String className = rpcRequest.getClassName();
            String methodName = rpcRequest.getMethodName();
            Class clazz = Class.forName(className);

//        需要修改为从spring容器中获取
//        if(className.equals(UserService.class.getName())){
//            className = className + "Impl";
//        }
//        Object obj = clazz.newInstance();
            Object obj = applicationContext.getBean(clazz);

            Method method = clazz.getMethod(methodName, rpcRequest.getParameterTypes());
            result = method.invoke(obj, rpcRequest.getParameters());
        } catch (Exception e) {
            exception = e;
            logger.error("调用{}类的{}方法{}时发生错误，参数为{}，错误原因{}", rpcRequest.getClassName(),
                    rpcRequest.getMethodName(), rpcRequest.getParameters(), e.getMessage());
        } finally {
            RpcResponse rpcResponse = new RpcResponse();
            rpcResponse.setCode(exception == null ? 200 : 500);
            rpcResponse.setRequestId(rpcRequest.getRequestId());
            rpcResponse.setException(exception);
            rpcResponse.setResult(result);
            ctx.writeAndFlush(rpcResponse);
        }

        // 判断是否符合约定，符合则调用本地方法，返回数据
        // msg:  UserService#sayHello#are you ok?
//        if(msg.toString().startsWith("UserService")){
//            UserServiceImpl userService = new UserServiceImpl();
//            String result = userService.sayHello(msg.toString().substring(msg.toString().lastIndexOf("#") + 1));
//            ctx.writeAndFlush(result);
//        }


    }
}
